// goods/pages/shoppingCart/shoppingCart.js
let myRequest = require('../../../common/script/myRequest.js');
let api = require('../../../common/script/api.js');
let utils = require('../../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: null,
    checkAll: false,
    startX: '',
    startY: '',
  },
  getData(cart_form_data = []) {
    const that = this;
    let data = {
      cart_form_data,
      select_store_id: wx.getStorageSync('select_store_id')
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.cartList, data).then(res => {
      wx.stopPullDownRefresh();
      wx.hideNavigationBarLoading();
      wx.hideLoading();
      if (res.data.status == 1) {
        res.data.result.storeList.forEach(item => {
          let checked = item.cartList.every(i => { // 检测商店全选状态
            return i.selected
          })
          item.checked = checked;
        })
        let checkAll = res.data.result.storeList.every(item => { // 检测全选状态
          return item.checked;
        })
        that.setData({
          formData: res.data.result,
          checkAll
        })
      }
    })
  },
 //跳转到生成订单页
 toCreateOrder() {
  const that = this;
  wx.navigateTo({
    url: `/goods/pages/createOrder/createOrder`,
  })
},
  // 全选
  pitchAll() {
    const that = this;
    let checkAll = that.data.checkAll;
    let storeList = that.data.formData.storeList || [];
    let listStates = [];
    storeList.forEach((item, index) => {
      item.checked = !checkAll
      listStates[index] = item.cartList.filter((data) => {
        data.selected = !checkAll
      })
    })

    that.setData({
      [`formData.storeList`]: storeList,
      checkAll: !checkAll
    })
    that.debounceMyEvents()
  },
  //单选
  pitch(e) {
    const that = this;
    let storeIndex = e.currentTarget.dataset.storeindex;
    let lists = that.data.formData.storeList[storeIndex].cartList;
    lists.map((data) => {
      data.selected = that.data.formData.storeList[storeIndex].checked ? 0 : 1
    })
    let storeList = that.data.formData.storeList || [];
    let listStates = [];
    storeList.forEach((item, index) => {
      listStates[index] = item.cartList.every((data) => {
        return data.selected
      })
    })
    let checkAll = listStates.every(item => {
      return item
    })
    that.setData({
      [`formData.storeList[${storeIndex}].checked`]: !that.data.formData.storeList[storeIndex].checked,
      [`formData.storeList[${storeIndex}].cartList`]: lists,
      checkAll
    })
    that.debounceMyEvents()
  },
  toDelete(e) {
    const that = this;
    const id = e.currentTarget.dataset.id;
    let data = {
      ids: id,
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.delCart, data).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        that.getData()
      }
    })
  },
  // 选中一个商品
  switchGoodDetail(e) {
    const that = this;
    let index = e.currentTarget.dataset.index;
    let storeIndex = e.currentTarget.dataset.storeindex;
    let lists = that.data.formData.storeList[storeIndex].cartList;

    lists[index].selected = lists[index].selected ? 0 : 1;
    let storeList = that.data.formData.storeList || [];
    let listStates = [];
    storeList.forEach((item, index) => {
      listStates[index] = item.cartList.every((data) => {
        return data.selected
      })
    })
    let checkAll = listStates.every(item => {
      return item
    })
    that.setData({
      [`formData.storeList[${storeIndex}].cartList`]: lists,
      checkAll
    })
    var boot = lists.some((data) => {
      return !data.selected
    })
    if (boot) {
      that.setData({
        [`formData.storeList[${storeIndex}].checked`]: false
      })
    } else {
      that.setData({
        [`formData.storeList[${storeIndex}].checked`]: true
      })
    }
    that.debounceMyEvents()
  },
  debounceMyEvents: utils.debounce(function (storeIndex, index) {
    const that = this;
    that.getData(that.getFormData(), storeIndex, index);
  }, 500),
  // 点击加减
  myevents(e) {
    const that = this;
    let index = e.currentTarget.dataset.index;
    let storeIndex = e.currentTarget.dataset.storeindex;
    let val = e.detail.val;
    that.setData({
      [`formData.storeList[${storeIndex}].cartList[${index}].goods_num`]: val
    })
    this.debounceMyEvents(storeIndex, index)
  },
  // 获取cart_form_data
  getFormData() {
    const that = this;
    let mydata = that.data.formData.storeList;
    let arr = [];
    mydata.forEach(item => {
      item.cartList.forEach(i => {
        let obj = {
          storeId: item.store_id,
          cartID: i.id,
          goodsNum: i.goods_num,
          selected: i.selected
        }
        arr.push(obj);
      })
    })
    return JSON.stringify(arr);
  },
  /**
   * 手指触摸动作开始 记录起点X坐标
   */
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.formData.storeList.forEach(data => {
      data.cartList.forEach(function (v, i) {
        if (v.isTouchMove)
          //只操作为true的
          v.isTouchMove = false;
      });
    })

    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      formData: this.data.formData
    });
  },
  /**
   * 滑动事件处理
   */
  touchmove: function (e) {
    let that = this,
      id = e.currentTarget.dataset.id, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    this.data.formData.storeList.forEach(data => {
      data.cartList.forEach(function (v, i) {
        v.isTouchMove = false;
        //滑动超过30度角 return
        if (Math.abs(angle) > 30) return;
        if (v.id == id) {
          if (touchMoveX > startX)
            //右滑
            v.isTouchMove = false;
          //左滑
          else v.isTouchMove = true;
        }
      });
    })
    //更新数据
    that.setData({
      formData: this.data.formData
    });
  },
  /**
   * 计算滑动角度
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y;
    //返回角度 /Math.atan()返回数字的反正切值
    return (360 * Math.atan(_Y / _X)) / (2 * Math.PI);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;
    that.getData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    const that = this;
    that.setData({
      noData: false,
      isEnd: false,
      page: 1
    })
    that.getData()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})